package org.iqiyi.util;

import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;

/**
 * @Auther: huqi
 * @Date: 2021/3/2: 14:59
 * @Description:返回前端的统一类
 */
@Data
public class JsonResult<T> implements Serializable {
    private static final long serialVersionUID = -8847260026696169235L;
    /***
     * 默认的操作值
     */
    private static final String SUCCESS_CODE = "0";
    private static final String SUCCESS_MSG = "操作成功";
    private static final String SUCCESS_STATUS = "success";

    private static final String FAIL_CODE = "9999";
    private static final String FAIL_MSG = "操作失败";
    private static final String FAIL_STATUS = "fail";

    /**
     * 操作状态  提示 成功还是失败
     */
    private String status = SUCCESS_STATUS;
    /*
      具体的一些后台返回给前端的消息
     */
    private String msg = SUCCESS_MSG;
    /*
     返回的操作码  可以供前端根据不同的状态码进行判断
     */
    private String code = SUCCESS_CODE;


    private Long count = 0L;
    /*
    数据
     */
    private T data;

    public T getData() {
        return this.data;
    }

    public JsonResult() {
    }

    /**
     * 只是返回成功  可以不带数据
     *
     * @return
     */
    public static <T> JsonResult<T> success() {
        return new JsonResult<>();
    }


    /**
     * 返回前端成功的消息和状态码都自定义
     *
     * @param message
     * @return
     */
    public static JsonResult success(String message, String code) {
        JsonResult success = JsonResult.success();
        success.setMsg(message);
        success.setCode(code);
        return success;
    }

    public static <T> JsonResult<T> success(T data) {
        JsonResult<T> success = JsonResult.success();
        success.setData(data);
        return success;
    }

    /**
     * 操作失败
     *
     * @return
     */
    public static JsonResult fail() {
        return JsonResult.fail(FAIL_MSG);
    }

    /**
     * 操作失败自定义消息
     *
     * @return
     */
    public static JsonResult fail(String message) {
        return JsonResult.fail(message, null);
    }

    /**
     * 操作失败自定义消息和状态码
     *
     * @return
     */
    public static JsonResult fail(String message, String code) {
        JsonResult jsonResult = new JsonResult();
        jsonResult.setStatus(FAIL_STATUS);
        if (StringUtils.isNotBlank(message)) {
            jsonResult.setMsg(message);
        } else {
            jsonResult.setMsg(FAIL_MSG);
        }
        if (StringUtils.isNotBlank(code)) {
            jsonResult.setCode(code);
        } else {
            jsonResult.setCode(FAIL_CODE);
        }
        return jsonResult;
    }


}
